<?php


namespace app\service;


use think\response\Json;
use \app\model\ArticleModel;

class articleStatisticsService
{


    // 文章统计
    public static function articleStatistics(string $uid): Json
    {
        try {
            $articleModel = new ArticleModel();
            // 获取所有文章
            $list = $articleModel->where('uid', $uid)->withCount(['articleLinke', 'articleCollect'])->select();


            print_r('1');
            $jsonList = [
                //文章数量
                'articleList' => $list->count(),
                // 文章点赞数
                'articleLink' => 0,
                //文章收藏数量
                'collects' => 0,
                // 上周和本周
                'weekData' => []
            ];


            foreach ($list as $article) {
                //点赞
                $jsonList['articleLink'] += $article->article_linke_count;
                //收藏
                $jsonList['collects'] += $article->article_collect_count;
            }
            //上周本周文章点赞
            $jsonList['weekData'] = articleStatisticsService::lastWeekAndWeek($uid);

            return \json(['code' => 200, 'data' => $jsonList], 200);
        } catch (\Exception $e) {
            return \json(['code' => 500, 'msg' => $e->getMessage()], 500);
        }

    }

    //上周和本周文章点赞量
    public static function lastWeekAndWeek(string $uid): array
    {
        $articleModel = new ArticleModel();
        // 查询上周点赞
        $lastList = $articleModel->where('uid', $uid)->whereWeek('issueTime', 'last week')
            ->withCount(['articleLinke'])->select();
        // 本周点赞
        $thisWeek = $articleModel->where('uid', $uid)->whereWeek('issueTime')
            ->withCount(['articleLinke'])->select();

        $lastArr = [];
        $weekArr = [];
        foreach ($lastList as $last) {
            array_push($lastArr, $last->article_linke_count);
        }
        foreach ($thisWeek as $last) {
            array_push($weekArr, $last->article_linke_count);
        }
        return ['last' => $lastArr, 'now' => $weekArr];
    }
}